package com.mic.yzzn.plc.common.instructions.basic;

import java.util.ArrayList;

import org.apache.commons.lang.StringUtils;

/**
 * Created by ASH on 16/3/7.
 */
abstract public class PLCRequestInstruction extends PLCInstruction
{
    public static final String
            PLCInstructionTypeRequestCode ="#";

    public static final String
            READ_SINGLE_CONTACTOR_INS = "RCS",
            READ_PLURAL_CONTACTOR_INS = "RCP",
            READ_WORD_UNIT_CONTACTOR_INS = "RCC",
            READ_DATA_AREA_INS = "RD",
            READ_PROGRAM_INS = "RP";

    public static final String
            WRITE_SINGLE_CONTACTOR_INS = "WCS",
            WRITE_PLURAL_CONTACTOR_INS = "WCP",
            WRITE_WORD_UNIT_CONTACTOR_INS = "WCC",
            WRITE_DATA_AREA_INS = "WD",
            WRITE_PROGRAM_INS = "WP";
    
    private static ArrayList<String> INS_READ_CODE;

    /** 请求代码 e.g RCS*/
    protected String requestCode;
    
    /**
     * 返回该条指令是否是读取指令
     * @return 是否是读取指令
     */
    public boolean isRead()
    {
    	return readInsturctionsCode().contains(requestCode);
    }
    
    static public ArrayList<String> readInsturctionsCode()
	{
		if (INS_READ_CODE == null)
		{
			INS_READ_CODE = new ArrayList<>();
			INS_READ_CODE.add(READ_SINGLE_CONTACTOR_INS);
			INS_READ_CODE.add(READ_PLURAL_CONTACTOR_INS);
			INS_READ_CODE.add(READ_WORD_UNIT_CONTACTOR_INS);
			INS_READ_CODE.add(READ_DATA_AREA_INS);
			INS_READ_CODE.add(READ_PROGRAM_INS);
		}
		
		return INS_READ_CODE;
	}
    
    /**
     * 返回该条指令是否是写指令
     * @return 是否是写指令
     */
    public boolean isWrite()
    {
    	return !isRead();
    }

    /**
     * 初始化方法
     */
    public PLCRequestInstruction()
    {
        this.instructionTypeCode = PLCInstructionTypeRequestCode;
    }

    /**
     * 请求码get方法
     * @return 请求码
     */
    public String getRequestCode()
    {
        return requestCode;
    }

    /**
     * 计算并返回自己的异或值
     */
    @Override
    protected int getXORByBit()
    {
        int i = 0;
        int result = 0;
        for (i = 0; i < requestCode.length(); ++i)
        {
            result ^= requestCode.charAt(i);
        }

        return super.getXORByBit() ^ result;
    }

    @Override
    protected String initWithString(String instructionString) throws IllegalArgumentException
    {
    	String tempResult =  super.initWithString(instructionString);
    	
//    	System.out.println(tempResult);
    	
    	// 检测请求类型码是否正常
    	if (!(tempResult.substring(0, 1).equals(instructionTypeCode)))
		{
			throw new IllegalArgumentException("request instruction type code must be \"#\"");
		}
    	
    	// 截取请求类型码
    	tempResult = StringUtils.substringAfter(tempResult, instructionTypeCode);
    	
    	return tempResult;
    }
}
